<template>
  <div class="progress-bar" ref="progressdiv" @click="progressClick">
    <div class="bar-inner">
      <div class="progress" ref="progress"></div>
      <div class="progress-btn-wrapper" ref="progressBtn" @touchstart.prevent="progressTouchStart" @touchmove.prevent="progressTouchMove"
        @touchend="progressTouchEnd">
        <div class="progress-btn"></div>
      </div>
    </div>
  </div>
</template>

<script>
  const progressBtnWidth = 12
  export default {
    name: 'ProgressBar',
    props: {
      percent: {
        type: Number,
        default: 0
      }
    },
    methods: {
      progressTouchStart(e) {
        this.touch.initiated = true
        this.touch.startX = e.touches[0].pageX
        this.touch.left = this.$refs.progress.clientWidth
      },
      progressTouchMove(e) {
        if (!this.touch.initiated) {
          return
        }
        const x = e.touches[0].pageX - this.touch.startX
        const offestX = Math.min(this.boxWith, Math.max(0, this.touch.left + x))
        this._go(offestX)
      },
      progressTouchEnd() {
        this.touch.initiated = false
        this._triggerPercent()
      },
      // 点击
      progressClick(e) {
        const rect = this.$refs.progressdiv.getBoundingClientRect()
        const offsetWidth = e.pageX - rect.left
        this._go(offsetWidth)
        // 当点击圆形按钮时候无法正确获取值
        // this._go(e.offsetX)
        this._triggerPercent()
      },
      _go(smallWith) {
        this.$refs.progress.style.width = `${smallWith}px`
        this.$refs.progressBtn.style['transform'] = `translate3d(${smallWith}px,0,0)`
      },
      _triggerPercent() {
        const percent = this.$refs.progress.clientWidth / this.boxWith
        this.$emit('percentChane', percent)
      }
    },
    watch: {
      percent(newPercent) {
        if (newPercent >= 0 && !this.touch.initiated) {
          this.boxWith = this.$refs.progressdiv.clientWidth - progressBtnWidth
          const smallWith = newPercent * this.boxWith
          this._go(smallWith)
        }
      }
    },
    created() {
      this.touch = {}
      this.boxWith
    },
  }

</script>
